import threading
import tkinter as tk
from tkinter import ttk, simpledialog, messagebox, Frame

import pygetwindow as gw

from screen_preview import update_preview
from screen_recorder import record_screen, stop_recording


def get_window_titles():
    # 获取所有可见窗口的标题列表
    return [window.title for window in gw.getAllWindows() if window.visible and window.title]


def start_recording():
    mode = mode_var.get()  # 获取用户选择的录制模式
    if mode == 'window':
        window_title = window_var.get()  # 获取用户选择的窗口标题
        # 在新线程中启动录制，以免阻塞UI
        threading.Thread(target=record_screen, args=(mode, window_title)).start()
    elif mode == 'custom':
        # 对于自定义区域，通过对话框让用户输入坐标
        x1 = simpledialog.askinteger("Custom Area", "Enter X1:")
        y1 = simpledialog.askinteger("Custom Area", "Enter Y1:")
        x2 = simpledialog.askinteger("Custom Area", "Enter X2:")
        y2 = simpledialog.askinteger("Custom Area", "Enter Y2:")
        threading.Thread(target=record_screen, args=(mode, None, (x1, y1, x2, y2))).start()
    else:
        # 全屏录制不需要额外参数
        threading.Thread(target=record_screen, args=mode).start()


def end_recording():
    filename = simpledialog.askstring("保存文件", "输入视频的文件名：")
    if filename:
        filename += '.mp4'  # 添加文件扩展名
        stop_recording(filename)  # 假设这是你的停止录制函数
    else:
        messagebox.showerror("错误", "保存视频需要文件名！")


def on_mode_change(selection):
    mode = mode_var.get()
    if mode == 'window':
        window_menu.pack(pady=10)
        window_var.set('Select Window')  # Reset to default or the first entry
    else:
        window_menu.pack_forget()


# 初始化Tkinter窗口
app = tk.Tk()
app.title("SK ScreenCapturePro")  # 窗口标题
app.geometry("600x300")  # 设置窗口的初始大小为 500 宽 x 300 高

# 创建两个Frame，一个用于预览，一个用于控制
preview_frame = Frame(app, width=400, height=300, bg='black')
controls_frame = Frame(app, width=300, height=300)

preview_frame.pack(side='left', fill='both', expand=True)
controls_frame.pack(side='right', fill='both', expand=True)

# 在预览框架中放置一个标签用于显示预览
preview_label = tk.Label(preview_frame)
preview_label.pack(expand=True, fill='both')

# 调用 screen_preview.py 中的 update_preview 函数开始显示屏幕预览
# update_preview(preview_label)

# 创建并设置模式选择的下拉菜单
mode_var = tk.StringVar()
mode_var.set("full_screen")  # 默认选项为全屏
mode_options = ["full_screen", "window", "custom"]
mode_menu = ttk.OptionMenu(controls_frame, mode_var, mode_var.get(), *mode_options, command=on_mode_change)
mode_menu.pack(pady=10)

# 创建并设置窗口选择的下拉菜单
window_var = tk.StringVar()
window_options = get_window_titles()
window_menu = ttk.OptionMenu(controls_frame, window_var, "Select Window", *window_options)
window_menu.pack_forget()

# 开始录制按钮
start_button = tk.Button(controls_frame, text="开始录制", command=start_recording)
start_button.pack(pady=20)

stop_button = tk.Button(controls_frame, text="停止录制", command=end_recording)
stop_button.pack(pady=10)

app.mainloop()  # 运行主事件循环
